package com.gec.web;

import com.gec.domain.User;
import com.gec.service.UserService;
import com.gec.service.impl.UserServiceImpl;
import com.gec.utils.CrossRegion;
import com.gec.utils.PageModel;
import com.gec.utils.TokenUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = {"/login","/findUserByPage","/userinfo","/saveUser","/findById","/updateUser","/deleteUser","/logout"})
public class UserController extends HttpServlet {
    //service对象
    UserService service = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //跨域设置
        CrossRegion.setCross(resp);
        //如果是get,设置200ok
        if ("OPTIONS".equals(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        //请求的servlet 路径
        String servletPath = req.getServletPath();

        //判断
        if(servletPath.equals("/login")){
            logins(req,resp);
        }else if(servletPath.equals("/userinfo")){
            userinfo(req,resp);
        }else if(servletPath.equals("/findUserByPage")){
            findallusers(req,resp);
        }else if(servletPath.equals("/saveUser") ||  servletPath.equals("/updateUser")){//判断到底是添加还是修改
            saveorupdateuser(req,resp);
        }else if(servletPath.equals("/findById")){
            findbyid(req,resp);
        }else if(servletPath.equals("/deleteUser")){
            deleteuser(req,resp);
        } else if (servletPath.equals("/logout")) {
            logout(req,resp);
        }

    }

    /**
     * 登录
     * */
    private void logins(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获得用户名密码
        String loginname = req.getParameter("loginname");
        String password = req.getParameter("password");
        User user = service.login(loginname,password);
        System.out.println("hhghgkhgh");
        System.out.println(loginname);
        System.out.println(password);
        //判断
        if(user != null){
            //传入用户名返回一个token
            String token = TokenUtils.getToken(loginname);//错误的 user.getLoginname()
            System.out.println("生成的token:" + token);

            user.setToken(token);
            //设置到响应头
            resp.setHeader("token",user.getToken());
            //设置状态
            resp.setStatus(200);


            Map<String,Object> map = new HashMap<>();
            map.put("token",user.getToken());
            map.put("code",200);
            map.put("userId",user.getId());
            map.put("message","success");
            //组装json
            Gson gson = new Gson();
            String json = gson.toJson(map);
            //响应json到前台
            resp.getWriter().write(json);
        }else{
            resp.getWriter().write("用户名密码错误");
        }
    }
    /**
     * 登录
     * */
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            Map<String,Object> map = new HashMap<>();
            map.put("code",200);
            map.put("message","success");
            //组装json
            Gson gson = new Gson();
            String json = gson.toJson(map);
            //响应json到前台
            resp.getWriter().write(json);
    }
    /**
     * 添加效果图
     * */
    private void userinfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println(".....进来userinfo.....");
        String loginname = req.getParameter("loginname");

        //接收token
        String token1 = req.getParameter("token");
        //检查（较验）
        boolean b = TokenUtils.checkToken(token1);
        //判断
        if(b){
            System.out.println("....有这个token.....");
            User user = service.findUserInfo(loginname);

            //组装Map
            Map<String,Object> map = new HashMap<>();
            map.put("usr",user);
            map.put("token",token1);
            map.put("code",200);
            map.put("roles","[admin]");
            map.put("name","admin");
            map.put("avatar","https://dingyue.ws.126.net/p7G6ckOFqUboE9ilHOPoVx90kuiljyND7Rfto=H43nroW1543656422098.gif");
            map.put("message","success");
            //组装json
            Gson gson = new Gson();
            String json = gson.toJson(map);
            //响应json到前台
            resp.getWriter().write(json);
        }
    }

    /**
     * 添加 修改
     * */
    private void saveorupdateuser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");

        String username = req.getParameter("username");
        String loginname = req.getParameter("loginname");
        String password = req.getParameter("password");

        User user=new User();
        user.setLoginname(loginname);
        user.setUsername(username);
        user.setPassword(password);

        user.setCreatedate(new Date());

        //如果id为0，则添加
        if (id.equals("0")) {
            user.setStatus(2);
            service.addUser(user);
        }else{//反之则修改
            int uid=Integer.parseInt(id);
            user.setId(uid);
            service.updateUser(user);
        }

        Map<String ,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("message","success");

        Gson gson=new Gson();
        String json = gson.toJson(map);
        resp.getWriter().write(json);
    }

    /**
     * 根据id查询
     * */
    private void findbyid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从页面获取id
        //int id=Integer.parseInt(req.getParameter("id"));
        // System.out.println(id);
        //返回到数据库
        User user = service.findById(Integer.parseInt(req.getParameter("id")));

        Map<String,Object>map=new HashMap<>();
        map.put("code",200);
        map.put("user",user);

        Gson gson=new Gson();
        String json = gson.toJson(map);

        resp.getWriter().write(json);
    }

    /**
     * 删除
     * */
    private void deleteuser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        service.delete(Integer.parseInt(id));

        Map<String,Object>map=new HashMap<>();
        map.put("code",200);

        Gson gson=new Gson();
        String json = gson.toJson(map);
        resp.getWriter().write(json);
    }

    /**
     * 查询全部 分页
     * */
    private void findallusers(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获得当前页码
        String pageIndex = req.getParameter("pageIndex");
        int page = !"".equals(pageIndex) && pageIndex != null ? Integer.parseInt(pageIndex) : 1;
        //设置到PageModel
        PageModel model = new PageModel();
        model.setPageIndex(page);

        //查询用户列表
        List<User> users = null;

        //查询用户名
        String lgname = req.getParameter("lgname");
        User user = new User();
        user.setLoginname(lgname);

        //总记录数
        int count = service.getTotalUserCount(user);
        model.setTotalRecoreSum(count);
        users = service.findAllUsers(user,model);

        Map<String,Object> map = new HashMap<>();
        map.put("model",model);
        map.put("users",users);

        //使用json返回
        Gson gson =new Gson();
        String s = gson.toJson(map);
        //响应前台
        resp.getWriter().write(s);

    }
}
